﻿Ext.define('App.desktop.DesktopLayout', {
    extend: 'Ext.layout.AnchorLayout',
    alias: 'layout.desktopLayout',
    monitorResize: true,

    onLayout: function () {

        var me = this;
        me.callParent();

        var view = me.owner,
        conf = view.desktop.conf,
        iconWidth = conf.IconWidth,
        iconHeight = conf.IconHeight,
        xSpacing = conf.XSpacing,
        ySpacing = conf.XSpacing,

        // Set the size of the panel
        height = view.getClientHeight(),

        // Compute the width taken by the icons
        sh = ySpacing + iconHeight + 1,
        v = Math.floor(height / sh) - 1, // Number of icons on Y
        n = view.items.length, // Total of icons
        r = n % v, // Remainder of icons that go to the next column
        x = r > 0 ? 1 : 0, // The extra column if a remainder
        h = Math.round(n / v) + x, // The number of columns
        w = h * (iconWidth + xSpacing + 1), // The horizontal width

        width = Math.max(view.getClientWidth(), w);

        view.setSize(width, height);

        // Position the icons
        var curX = xSpacing, curY = ySpacing;

        view.items.each(function (item) {

            item.getEl().position('absolute', null, curX, curY);

            if (curY + 4 * ySpacing > height) { // Vertical overflow
                curX += iconWidth + xSpacing; // Move to the right
                curY = ySpacing; // Move to top
            }
            else {
                curY += iconHeight + ySpacing;
            }

        });
    }

});